<?
class Library {
	var $htmlString;
	
	function getLibraryListRSS($idType=null,$idItem=null) {
		global $dbname, $db, $db_selected;
		$today = date('Y-m-d');
		
		if (empty($idType) && empty($idItem)) {
			
		} elseif ($idType == 'cat') {
			
		} elseif ($idType == 'tag') {
			
		}
		
		$sql = "SELECT * from cdc_LibraryMediaList 
				ORDER BY DateUpdate DESC
				LIMIT 20";
		$result = mysql_db_query($dbname,$sql);
		
		while ($value = mysql_fetch_array($result)) {
			$eventID    = $value['EventID'];
			$eventTitle = stripslashes($value['EventName']);
			$eventDesc  = stripslashes($value['EventDescription']);
			$eventDesc  = shortText($eventDesc,20);
			$register   = $value['RegistrationRequired'];
			$regURL     = $value['RegistrationLink'];
			
			$dateUpdate = new Zend_Date($value['DateUpdate'],'en');
			$newDateUpdate = $dateUpdate->toString('EEE, d MMM YYYY 00:00:00 GMT');
			
			$this->rssString .= '<item>';
			$this->rssString .= '<title>'.$eventTitle.'</title>';
			$this->rssString .= '<link>http://www.childdisabilityconnection.org/events.php?eventID='.$eventID.'</link>';
			$this->rssString .= '<pubDate>'.$newDateUpdate.'</pubDate>';
			$this->rssString .= '<description>[CDATA[ ]]</description>';
			$this->rssString .= '</item>';			
		}	
		return $this->rssString;
	}
	
	function searchLibrary($searchTerm=null) {
		global $dbname, $db, $db_selected;
		$searchTerm = fieldToDB($searchTerm);
		
		$searchTermArray = explode(' ',$searchTerm);
		$timeStart = microtime_float();
		
		$sql = "SELECT 
					LibraryID,
					Authors,
					Title,
					Abstract,
					MATCH (Authors,Title,Abstract,Publisher,Tags) AGAINST
					('\"$searchTerm\"') AS searchScore
					FROM cdc_LibraryMediaList 
					WHERE  
						( MATCH (Authors,Title,Abstract,Publisher,Tags) AGAINST ('\"$searchTerm\"' IN BOOLEAN MODE) ) 
					ORDER BY searchScore DESC";
		$result = mysql_db_query($dbname,$sql);
		$rows = mysql_num_rows($result);
		
		if ($rows<1) {		
			$sql = "SELECT 
						LibraryID,
						Authors,
						Title,
						Abstract,
						MATCH (Authors,Title,Abstract,Publisher,Tags) AGAINST
						('$searchTerm') AS searchScore
						FROM cdc_LibraryMediaList 
						WHERE ( 
								( MATCH (Authors,Title,Abstract,Publisher,Tags) AGAINST ('$searchTerm' IN BOOLEAN MODE) ) OR 
						
								( 
									Authors   LIKE '%$searchTerm%' OR 
									Title     LIKE '%$searchTerm%' OR 
									Abstract  LIKE '%$searchTerm%' OR
									Publisher LIKE '%$searchTerm%'
								) 
							) 
						ORDER BY searchScore DESC";
			$result = mysql_db_query($dbname,$sql);
			$rows = mysql_num_rows($result);
		}	
		$timeEnd = microtime_float();	
		$timeElapsed = ($timeEnd-$timeStart)*1000;
		$timeElapsedDisplay = round($timeElapsed,1);
		
		/*
		 * Log search data to database
		 */
		$sqlSD = "INSERT into cdc_sysSearchData (
						MemberID,
						SearchTerm,
						NoOfResults,
						ExecuteTime,
						DateSearch
					) values (
						'".$_SESSION['memberID']."',
						'$searchTerm',
						'$rows',
						'$timeElapsedDisplay',
						'".date('Y-m-d')."'
					)";
		$resultSD = mysql_db_query($dbname,$sqlSD);
		
		if ($rows>0) {
			$j=0;
			
			$this->htmlString .= '<div class="hiLite" style="padding: 3px;"><p style="text-align: right; width: 100%;"><b>'.$rows.'</b> items found in '.$timeElapsedDisplay.' milliseconds.</p></div>';
			while ($value = mysql_fetch_array($result)) {
				if (($j%2)>0) {
					$rowClass = 'altRow';
				} else {
					$rowClass = '';
				}
				$itemRender = $this->renderLibraryListItem($value,$rowClass);
				//$itemRender = highlightWords($itemRender,$searchTermArray);
				$itemRender = highlightTerm($itemRender,$searchTerm);
				$this->htmlString .= $itemRender;
				$j++;
			}			
		} else {
			$this->htmlString .= 'Your search for <b>'.$searchTerm.'</b> did not find any library items. Please try another search.';	
		}
		return $this->htmlString;
	}
	
	function getNumberOfItems($itemType,$item) {
		global $dbname, $db, $db_selected;
		
		if ($itemType == 'category') {
			$where = " WHERE CatID = '$item' ";
		} elseif ($itemType == 'tag') {
			$where = " WHERE Tags LIKE '%$item%' ";
		}
		
		$sql = "SELECT COUNT(LibraryID) AS LibraryItems 
				FROM cdc_LibraryMediaList
				$where ";
		$result = mysql_db_query($dbname,$sql);
		$row = mysql_fetch_assoc($result);
		$libraryItems = $row['LibraryItems'];
		return $libraryItems;
	}
	
	function getLibraryCategories($limitView=0) {
		global $dbname, $db, $db_selected;

		$sql = "SELECT C.CatID,C.CatTitle,COUNT(L.LibraryID) AS NumberItems
				FROM cdc_sysCategory C
				LEFT JOIN cdc_LibraryMediaList L ON C.CatID = L.CatID
				WHERE 
				C.SiteArea = 'Library' 
				GROUP BY C.CatID
				ORDER BY C.CatTitle";
		$result = mysql_db_query($dbname,$sql);
		$rows = mysql_num_rows($result);
		$j=0;
		while ($value = mysql_fetch_array($result)) {
			if ($value['NumberItems']>$limitView) {
				$catIDArray[$j] = $value['CatID'];
				$catNameArray[$j] = $value['CatTitle'];
				$noItemsArray[$j] = $value['NumberItems'];
				$j++;
			}				
		}
		$totalRows = ceil(($j-1)/2);
		
		$j=0;
		for($a=1;$a<=$totalRows;$a++) {
			for($b=0;$b<=1;$b++) {
				$noOfItems = $this->getNumberOfItems('category',$catIDArray[$j]);
				
				$this->htmlString .= '<div style="float: left; width: 48%;">';
				$this->htmlString .= '<p><a href="'.$_SERVER['PHP_SELF'].'?cat='.$catIDArray[$j].'" class="bigLink">'.$catNameArray[$j].'</a> <b class="grayText">( '.$noItemsArray[$j].' )</b></p>';
				if (!empty($catDescArray[$j])) {
					$this->htmlString .= '<p>'.$catDescArray[$j].'</p>';
				}
				$this->htmlString .= '</div>';
				$j++;
			}
			$this->htmlString .= '<div style="clear: left; height: 5px;"></div>';
		}
	}
	
	function getLibraryTags() {
	global $dbname, $db, $db_selected;

		$sql = "SELECT * from cdc_sysTags WHERE SiteArea = 'Library' ORDER BY TagName";
		$result = mysql_db_query($dbname,$sql);
		$rows = mysql_num_rows($result);
		$j=0;
		while ($value = mysql_fetch_array($result)) {
			$tagIDArray[$j]   = $value['TagID'];
			$tagNameArray[$j] = stripslashes($value['TagName']);
			$j++;
		}
		$j=$j-1;
		$totalRows = ceil($rows/2);
		
		$j=0;
		for($a=1;$a<=$totalRows;$a++) {
			for($b=0;$b<=1;$b++) {
				if (!empty($tagNameArray[$j])) {
					$noOfItems = $this->getNumberOfItems('tag',$tagNameArray[$j]);
					
					$this->htmlString .= '<div style="float: left; width: 48%;">';
					$this->htmlString .= '<p><a href="'.$_SERVER['PHP_SELF'].'?tag='.$tagNameArray[$j].'" class="bigLink">'.$tagNameArray[$j].'</a> <b class="grayText">( '.$noOfItems.' )</b></p>';
					$this->htmlString .= '</div>';
				}	
				$j++;
			}
			$this->htmlString .= '<div style="clear: left; height: 5px;"></div>';
		}
	}
	
	function getLibraryItemsByCategory($catID) {
		global $dbname, $db, $db_selected;
		
		$sql = "SELECT LibraryID,Authors,Title,Abstract
				FROM cdc_LibraryMediaList
				WHERE CatID = '$catID'
				ORDER BY Title";
		$result = mysql_db_query($dbname,$sql);

		$j=0;
		while ($value = mysql_fetch_array($result)) {
			if (($j%2)>0) {
				$rowClass = 'altRow';
			} else {
				$rowClass = '';
			}
			$this->htmlString .= $this->renderLibraryListItem($value,$rowClass);
			$j++;
		}
	}
	
	function getLibraryItemsByTag($tag) {
		global $dbname, $db, $db_selected;
		
		$sql = "SELECT LibraryID,Authors,Title,Abstract
				FROM cdc_LibraryMediaList
				WHERE Tags LIKE '%$tag%'
				ORDER BY Title";
		$result = mysql_db_query($dbname,$sql);
		
		$j-0;
		while ($value = mysql_fetch_array($result)) {
			if (($j%2)>0) {
				$rowClass = 'altRow';
			} else {
				$rowClass = '';
			}
			$this->htmlString .= $this->renderLibraryListItem($value,$rowClass);
			$j++;
		}
	}
	
	function getLibraryItem($itemID,$render='screen') {
		global $dbname, $db, $db_selected;
		
		$sql = "SELECT 
					L.LibraryID,L.ISBN,L.Authors,L.Title,L.Abstract,
					L.LanguageEnglish,L.LanguageSpanish,L.LanguageRussian,
					L.Tags,L.Publisher,L.InhouseViewingOnly,
					C.CatTitle
				FROM cdc_LibraryMediaList L
				LEFT JOIN cdc_sysCategory C ON L.FormatID = C.CatID
				WHERE LibraryID = '$itemID'
				ORDER BY Title";
		$result = mysql_db_query($dbname,$sql);
		$rowItem = mysql_fetch_assoc($result);
		
		if ($render == 'screen') {
			$this->htmlString .= $this->renderLibraryItem($rowItem);
		} elseif ($render == 'array') {
			return $rowItem;
		}	
	}
	
	function renderLibraryItem($itemArray) {
		$tagString = new Tags();
		global $translate;
		
		$itemID       = $itemArray['LibraryID'];
		$itemISBN     = $itemArray['ISBN'];
		$itemAuthors  = $itemArray['Authors'];
		$itemTitle    = stripslashes($itemArray['Title']);
		$itemAbstract = stripslashes($itemArray['Abstract']); 
		$langEnglish  = $itemArray['LanguageEnglish'];
		$langSpanish  = $itemArray['LanguageSpanish'];
		$langRussian  = $itemArray['LanguageRussian'];
		$itemFormat   = $itemArray['CatTitle'];
		$itemTags     = $itemArray['Tags'];
		$itemPublisher= $itemArray['Publisher'];
		$inHouseView  = $itemArray['InhouseViewingOnly'];
		
		/*
		 * Let's try to get some Amazon information for this item
		 */
		$amazonRequest  = AMAZON_BASE_URI.'&SubscriptionId='.AMAZON_SUBSCRIPTION_ID.'&AWSAccessKeyId='.AMAZON_API_KEY;
		$amazonRequest .= '&Operation=ItemSearch&SearchIndex=Books&Keywords='.$itemISBN.'&ResponseGroup=Images,ItemAttributes,Small';
		$response  = file_get_contents($amazonRequest);
		$amazonXML = simplexml_load_string($response);
		
		$link  = $amazonXML->Items->Item->DetailPageURL;
		$image = $amazonXML->Items->Item->MediumImage->URL;
		
		$this->htmlString .= '<h2 style="margin-top: 10px;">'.$itemTitle.'</h2>';
		$this->htmlString .= '<p style="margin-bottom: 20px;">by '.$itemAuthors.'</p>';
		
		if (!empty($image)) {
			$this->htmlString .= '<div class="imgLeft"><a href="'.$link.'" target="_blank"><img src="'.$image.'" class="imgBorder" title="'.$itemTitle.'" alt="'.$itemTitle.'" /></a><br />';
			$this->htmlString .= '<p class="imgCaption"><a href="'.$link.'" target="_blank">Buy from Amazon</a></p></div>';	
		}
		$this->htmlString .= '<p>';
		if (!empty($itemAbstract)) {
			$this->htmlString .= $itemAbstract;
		}
		
		if ($inHouseView == 1) {
			$this->htmlString .= '<div style="float: right;"><p style="padding: 5px;"><a href="" class="iconHome bigLink" title="'.$translate->_('This item must be viewed at one of our locations.').'">'.$translate->_('This item must be viewed at one of our locations.').'</a></p></div>';
			$this->htmlString .= '<div style="clear: right;"></div>';
		} else {
			if ($this->determineCheckoutStatus($_SESSION['userid'],$itemID) == 1) {
				$this->htmlString .= '<div style="float: right;"><p style="padding: 5px;"><a href="accountCreate.php?itemType=library&itemID='.$itemID.'" class="iconCheckout bigLink" title="'.$translate->_('Checkout this item').'">'.$translate->_('Checkout this item').'</a></p></div>';
				$this->htmlString .= '<div style="clear: right;"></div>';
			}
		}
		
		/*
		 * Render tags
		 */
		$this->htmlString .= '<div style="clear: left;"></div>';
		$this->htmlString .= $tagString->renderTagsForItem('library',$itemID);
		$this->htmlString .= '</p>';
	}
	
	function renderLibraryListItem($itemArray,$rowClass) {
		$itemID      = $itemArray['LibraryID'];
		$itemAuthors = $itemArray['Authors'];
		$itemTitle   = stripslashes($itemArray['Title']);
		$itemAbstract = stripslashes($itemArray['Abstract']);
		$searchScore  = $itemArray['searchScore'];
		
		if (!empty($itemAbstract)) {
			$itemAbstract = shortText($itemAbstract,30);
		}
		$itemString  = '<div class="'.$rowClass.'" style="padding: 8px;"><p><a href="libraryView.php?item='.$itemID.'" class="bigLink">'.$itemTitle.'</a></p>';
		$itemString .= '<p style="margin-bottom: 5px;"><i>by '.$itemAuthors.'</i></p>';
		$itemString .= '<p style="margin: 0 0 10px 15px;">'.$itemAbstract.'</p></div>';
		
		return $itemString;
	}
	
	function makeBreadcrumbs($breadcrumbType,$breadcrumbItem=null) {
		global $dbname, $db, $db_selected;
		
		if ($breadcrumbType == 'tag') {
			$breadcrumbString = '<a href="'.$_SERVER['PHP_SELF'].'?viewBy=tag" class="bigLink">Tags</a> / '.$breadcrumbItem;
		} elseif ($breadcrumbType == 'category') {
			$sql = "SELECT CatTitle from cdc_sysCategory WHERE CatID = '$breadcrumbItem'";
			$result = mysql_db_query($dbname,$sql);
			$row = mysql_fetch_assoc($result);
			
			$breadcrumbString = '<a href="'.$_SERVER['PHP_SELF'].'?viewBy=category" class="bigLink">Categories</a> / '.$row['CatTitle'];
		}
		return $breadcrumbString;
	}
	
	function determineCheckoutStatus($memberID=null,$itemID) {
		global $dbname, $db, $db_selected;
		global $translate;
		
		/*
		 * Checkout Status:
		 * Status 1 = not checked out
		 * Status 2 = checked out
		 * Status 3 = none available for checkout
		 */
		$checkoutStatus = 1;
		
		if (!empty($memberID)) {
			/*
			 * See if this user currently has this book checked out.
			 */
			$sql = "SELECT * from cdc_LibraryCheckOut
					WHERE
					LibraryID = '$itemID' AND
					MemberID  = '$memberID' AND
					NumberReturned = 0
					";
			$result = mysql_db_query($dbname,$sql);
			if (mysql_num_rows($result)>0) {
				/*
				 * 
				 */
				$checkoutStatus = 2;
			}
		}	
		return $checkoutStatus;
	}
	
	function determineReturnDate($memberID,$itemID) {
		global $dbname, $db, $db_selected;
				
		$sql = "SELECT * from cdc_LibraryCheckOut
					WHERE
					LibraryID = '$itemID' AND
					MemberID  = '$memberID'
					";
		$result = mysql_db_query($dbname,$sql);
		$row = mysql_fetch_assoc($result);
		
		$dateLent = $row['DateLent'];
		$today    = date('Y-m-d');
		
		$maxDays = LIBRARY_CHECKOUT_DAYS;
		$daysBetweenDates = daysBetweenDates($dateLent,$today);
		
		if ($daysBetweenDates == 0) {
			$daysOverdue = 0-LIBRARY_CHECKOUT_DAYS;					
		} elseif ($daysBetweenDates<$maxDays) {
			$daysOverdue = $maxDays-$daysBetweenDates;
		} elseif ($daysBetweenDates>$maxDays) {
			/*
			 * We're late returning this item
			 */
			$daysOverdue = $daysBetweenDates-$maxDays;			
		}
		return $daysOverdue;
	}
		
	function getCheckedOutBooksByMember($memberID) {
		
	}
	
	function renderLibraryHTML() {
		return $this->htmlString;
	}
}
?>